package com.oceansoft.mobile.biz.front.service;

import java.util.ArrayList;
import java.util.Random;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.oceansoft.mobile.biz.front.entity.Award;
import com.oceansoft.mobile.biz.front.entity.AwardMapper;
import com.oceansoft.mobile.biz.front.entity.Jp;
import com.oceansoft.mobile.biz.front.entity.JpMapper;
import com.oceansoft.mobile.common.dao.ICommonDao;
import com.oceansoft.mobile.common.util.Result;

@Service
public class AwardServiceImp implements IAwardService{
	@Resource
	private ICommonDao commonDao;

	/**
	 * 获得奖品的随机数组
	 * @param sum
	 * @return
	 */
	public int[] getArray(int sum) {
		Random random = new Random();
		int[] array = new int[sum];
		//定义随机数
		int num;
		//定义循环终止的标志
		boolean flag;
		//从0开始索引
		for (int i = 0; i < sum; i++) {
			//flag为真表示无限循环
			flag = true;
			//产生随机数
			num = random.nextInt(sum) + 1;
			while (flag) {
				int j = 0;
				for (j = 0; j < i; j++) {
					//当num与之前的数有重复则重新产生随机数
					if (array[j] == num) {
						num = random.nextInt(sum) + 1;
						break;
					}
				}
				//表示不存在重复，终止循环
				if (j == i) {
					flag = false;
				}
			}
			array[i] = num;
		}
		return array;
	}
	
	@Override
	public void initAward() {
		ArrayList<Jp> jps = (ArrayList<Jp>) commonDao.loadList("select * from wx_jp", new JpMapper());
		//奖品总数
		int sum = 0;
		int awards[] = new int[jps.size()];
		for(int i=0;i<jps.size();i++){
			sum += jps.get(i).getCount();
			awards[i] = sum;
		}
		
		int[] awardRandom = getArray(sum);
		for(int i=0;i<awardRandom.length;i++){
			//奖品类型1特等奖，2一等奖...
			int award_type;
			if(awardRandom[i] <= awards[0]){
				award_type = 1;
			}else if(awardRandom[i] <= awards[1]){
				award_type = 2;
			}else if(awardRandom[i] <= awards[2]){
				award_type = 3;
			}else if(awardRandom[i] <= awards[3]){
				award_type = 4;
			}else if(awardRandom[i] <= awards[4]){
				award_type = 5;
			}else{
				award_type = 6;
			}
			Jp jp = new Jp();
			jp.setId(award_type);
			commonDao.saveOne("INSERT INTO wx_price(sid,award_type,status) VALUES"
					+ "(null,:id,0)",jp);
		}
	}

	@Override
	public Result startAward() {
		String sql = "select * from wx_price where sid = (select min(sid) from wx_price where status = 0 order by sid asc)";
		Award award = commonDao.loadOne(sql, new AwardMapper(), null);
		if(award == null){
			return new Result(Result.FAILURE, award, "奖品已经抽完");
		}
		String sql_update = "update wx_price set status = 1 where sid = ?";
		commonDao.update(sql_update,award.getSid());
		return new Result(award);
	}

	@Override
	public Award getAward() {
		String sql = "select * from wx_price where sid = (select min(sid) from wx_price where status = 0 order by sid asc)";
		Award award = commonDao.loadOne(sql, new AwardMapper(), null);
		if(award != null){
			String sql_update = "update wx_price set status = 1 where sid = ?";
			commonDao.update(sql_update,award.getSid());
		}
		return award;
	}
	
	
}
